// stores/user.ts
import { defineStore } from 'pinia';

interface UserInfo {
  username: string;
  nickname: string;
  permissions: string[];
  token: string;
  avatar?: string; // 添加头像字段
}

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null as UserInfo | null,
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.userInfo?.token,
    
    // 获取用户头像URL
    userAvatarUrl: (state) => state.userInfo?.avatar || '',
    
    // 获取用户显示名称
    displayName: (state) => state.userInfo?.nickname || state.userInfo?.username || '',
    
    // 获取头像回退字符
    avatarFallback: (state) => {
      const name = state.userInfo?.nickname || state.userInfo?.username || 'U';
      return name.charAt(0).toUpperCase();
    },
  },
  
  actions: {
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
      // 保存token到localStorage
      if (userInfo.token) {
        localStorage.setItem('token', userInfo.token);
      }
      // 保存用户信息到localStorage（可选）
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    },
    
    clearUserInfo() {
      this.userInfo = null;
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
    },
    
    // 从localStorage恢复用户信息
    restoreUserInfo() {
      const token = localStorage.getItem('token');
      const userInfoStr = localStorage.getItem('userInfo');
      
      if (token && userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr);
          if (userInfo && userInfo.token === token) {
            this.userInfo = userInfo;
          }
        } catch (error) {
          console.error('恢复用户信息失败:', error);
          this.clearUserInfo();
        }
      }
    },
    
    hasPermission(permission: string): boolean {
      return this.userInfo?.permissions?.includes(permission) ?? false;
    },
  },
});